﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace CRC.Main.Formularios
{
    public partial class SmartComboBox : ComboBox
    {
        private Hashtable dicc = new Hashtable();

        public SmartComboBox()
        {
            InitializeComponent();
        }

        public void SetData(IList<Object[]> pDatos) 
        {
            dicc.Clear();
            base.Items.Clear();

            IEnumerator it = pDatos.GetEnumerator();
            while (it.MoveNext())
            {
                Object[] entrada = (Object[])it.Current;
                addItem(entrada[0], entrada[1]);
            }
        }

        public void addItem(Object pKey, Object pValue) {
            dicc.Add(pKey, pValue);
            base.Items.Add(pValue);
        }

        //public void removeItem(Object pValue)
        //{
        //    this.removeItem(pValue);
        //    IDictionaryEnumerator en = dicc.GetEnumerator();
        //    while (en.MoveNext()) 
        //    {
        //        if (en.Value.Equals(pValue)) {
        //            dicc.Remove(en.Key);
        //            return;
        //        }
        //    }
        //}

        public void removeItem(Object pKey)
        {
            if (dicc.Contains(pKey))
            {
                Object value = dicc[pKey];
                base.Items.Remove(value);
                dicc.Remove(pKey);
            }
        }

        public void setValue(Object pKey, Object pValue)
        {
            if (dicc.Contains(pKey))
            {
                Object value = dicc[pKey];
                int index = base.Items.IndexOf(pValue);
                base.Items[index] = pValue;
                dicc[pKey] = pValue;
            }
        }
        
        public Object SelectedKey
        {
            get {

                IDictionaryEnumerator en = dicc.GetEnumerator();
                while (en.MoveNext())
                {
                    if (en.Value == base.SelectedItem )
                    {
                        return en.Key;
                    }
                }

                return null;
            }

            set 
            {
                if (value != null)
                {
                    Object objValue = dicc[value];
                    base.SelectedItem = objValue;
                }
                else 
                {
                    base.SelectedIndex = -1;
                }
            }
        }
    }
}
